// homepages/personalpages/facerecognpage/facerecognpage.js
// const util = require('../../../utils/base64.js')
const util = require('../../../utils/util.js');
var app = getApp();
var interval = null //倒计时函数
Page({

  /**
   * 页面的初始数据
   */
  data: {
    facesrc: '/images/scan@2x.png', 
    imagesrc: '/images/info@2x.png',
    infomessage: '人脸识别时间时间为周一至周五8点到19点，请在该时间段进行验证',
    duration: 0,
    size: 0,
    height: 0,
    width: 0,
    src: '',
    getData: {},
    detailInfo: {},
    cal_time: '',

    fun_id: 2,
    time: '获取验证码', //倒计时 
    currentTime: 60,
    currentTimeseccess: 4,
    successsrc: '/images/success@2x.png',
    failsrc: '/images/fail@2x.png',
    showsuccessDialog: false,
    showfailDialog: false,
    successtimer: '',//定时器名字
    countDownNum: '3',//倒计时初始值
    ValiCd:'',//短信验证码
    txn_Rslt_Cd: '',//交易结果代码
    // fileUrl:"",//上传视频的返回地址
  

  },
  hidden:function(name) {
    var newStr;
    if (name.length== 2) {
      newStr = name.substr(0, 1) + '*';
    } else if (name.length > 2) {
      var char = '';
      for (let i = 0, len = name.length - 2; i < len; i++) {
        char += '*';
      }
      newStr = name.substr(0, 1) + char + name.substr(-1, 1);
    } else {
      newStr = name;
    }
    return newStr;
  },

  //短信验证码
  getVerificationCode() {
    this.setCountDown();//短信验证码倒计时方法
    // 短信验证码请求
    var that = this;
    console.log(this.data.inputVal);
    let url = app.globalRequestUrl('domainNameB', 'siteD');
    let data = {
      Mkt_ID: app.globalData.Mkt_ID,//市场编号
      WeCht_Idr: app.globalData.WeCht_Idr,//微信标识
    }
    app.appRequest('post', url, data, (res) => {
      var message = JSON.stringify(res);
      console.log('人脸识别验证码接口返回数据：' + message);
      if (res.Txn_Rslt_Cd == "00") {
        that.setData({
          ValiCd: res.ValiCd
        });
      } else if (res.Txn_Rslt_Cd == "02") {
        wx.redirectTo({
          url: '/typechoosepage/typechoosepage',
        })
      }else {
        app.showErrormessage(res.Err_Inf);
      }
    }, (err) => {
      console.log('请求错误信息：  ' + err.errMsg);
      app.showErrormessage(err.errMsg);
    });
  },

  //短信验证码倒计时方法
  setCountDown: function (options) {
    // 设置按钮不可点击
    var that = this
    that.setData({
      disabled: true
    })
    // 设置倒计时
    var that = this;
    var currentTime = that.data.currentTime
    interval = setInterval(function () {
      currentTime--;
      that.setData({
        time: currentTime + '秒'
      })
      if (currentTime <= 0) {
        clearInterval(interval)
        that.setData({
          time: '重新发送',
          currentTime: 61,
          disabled: false
        })
      }
    }, 1000)
  },
 
  //弹出失败对话框
  togglefailDialog() {
    this.failcountDown();
    this.setData({
      showfailDialog: !this.data.showfailDialog
    });

  },
  
  //失败弹窗倒计时
  failcountDown: function () {
    let that = this;
    let countDownNum = that.data.countDownNum;//获取倒计时初始值
    //如果将定时器设置在外面，那么用户就看不到countDownNum的数值动态变化，所以要把定时器存进data里面
    that.setData({
      timer: setInterval(function () {//这里把setInterval赋值给变量名为timer的变量
        //每隔一秒countDownNum就减一，实现同步
        countDownNum--;
        //然后把countDownNum存进data，好让用户知道时间在倒计着
        that.setData({
          countDownNum: countDownNum
        })
        //在倒计时还未到0时，这中间可以做其他的事情，按项目需求来
        if (countDownNum == 0) {
          //这里特别要注意，计时器是始终一直在走的，如果你的时间为0，那么就要关掉定时器！不然相当耗性能
          //因为timer是存在data里面的，所以在关掉时，也要在data里取出后再关闭
          clearInterval(that.data.timer);
          //关闭定时器之后，可作其他处理codes go her
          that.setData({
            showfailDialog: !that.data.showfailDialog,
            countDownNum: '3'
          });
        }
      }, 1000)
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //人脸识别事件处理函数
  bindButtonTap: function () {
    if (!app.facecheckIsEmpenty(this.data.ValiCd, '短信验证码')){
      var that = this
      wx.chooseVideo({
        sourceType: ['camera'],
        compressed: true,
        maxDuration: 60,
        camera: 'front',
        success: function (res) {
          console.log("人脸视频信息" + res);
          //跳转成功页面
          // wx.redirectTo({
          //   url: '/homepages/commonpages/successpage/successpage?type=1',
          // })
          var start_cal_time = util.formatTime(new Date());
          that.setData({
            src: res.tempFilePath,
            duration: res.duration,
            size: res.size,
            height: res.height,
            width: res.width
          })
          const videoTempPath = res.tempFilePath;
          var timeStr = util.formatTime(new Date());//格式化时间
          var Cst_ID = util.randomNum + util.mobileNumber;
          var endTime = new Date().getTime();// 视频结束的时间戳
          console.log("endTime:" + endTime);
          var startTime = endTime - that.data.duration * 1000;// 视频开始的时间戳
          console.log("startTime" + startTime);
          var date = new Date();
          var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours().toString();
          var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes().toString();
          var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds().toString();
          var ss = date.getMilliseconds();
          if (ss < 10) {
            ss = '00' + ss;
          } else if (ss < 100) {
            ss = '0' + ss;
          } else {
            ss = ss.toString()
          }
          var currentTime = h + m + s + ss;
          var location2 = "https://marketpay.ccb.com/wechat/OlSign/fileNewUpload";
          //var location2 = "http://marketpay.dev.jh/wechat/OlSign/fileNewUpload";
          console.log("url:" + location2);
          console.log("video:" + videoTempPath);
          console.log("currentTime:" + currentTime);
          //  var datajson= {
          //       // Mkt_ID: app.globalData.Mkt_ID,//市场编号
          //       "Mkt_ID": "41060860800084",//市场编号
          //         // WeCht_Idr: app.globalData.WeCht_Idr,//微信标识
          //         "WeCht_Idr": "oyTj25d5gD2doUNEXhC69Og6klwo",//微信标识
          //           "Pic_Tp": "04",//图片类型
          //             "Pic_Pgs": "1",//图片张数
          //               "Acq_Tm": currentTime//请求时间HHmmssSSS
          //     };
          var datajson = {
            "Ol_Sign_Jrnl_No": app.globalData.Ol_Sign_Jrnl_No,
            "Mkt_ID": app.globalData.Mkt_ID,
            "WeCht_Idr": app.globalData.WeCht_Idr,
            "Pic_Tp": "04",
            "Pic_Pgs": "1",
            "Acq_Tm": currentTime
          };
          var jsonStr = JSON.stringify(datajson);
          console.log("datajson:" + jsonStr);
          const uploadTask = wx.uploadFile({
            url: location2,
            filePath: videoTempPath,
            name: 'file',
            header: {
              "Content-Type": "multipart/form-data",
            },
            formData: {
              jsonStr: jsonStr
            },

            success: function (res) {
              console.log("上传视频文件接口" + JSON.stringify(res.data));
              console.log("-------1-------");
              var temp = JSON.parse(res.data);
              console.log("-------2-------");
              if (temp.Txn_Rslt_Cd == "02") {
                wx.redirectTo({
                  url: '/typechoosepage/typechoosepage',
                })
              } else if (temp.Txn_Rslt_Cd=="00"){
                console.log("上传视频文件接口返回的" + res.Txn_Rslt_Cd);
                that.faceReTap();
              } else if (temp.Txn_Rslt_Cd == "01"){
                app.showErrormessage(res.Err_Inf);
              }
            },
            fail: function (e) {
              console.log(e);
              app.showErrormessage(err.errMsg);
            },
            complete: function (res) {
              // console.log("complete:" + JSON.stringify(res))
              wx.hideLoading();
              var end_cal_time = util.formatTime(new Date());
              that.setData({
                cal_time: end_cal_time - start_cal_time
              })
            }
          })
          wx.showLoading({
            title: '正在上传图像'
          });

          uploadTask.onProgressUpdate(function (res) {
            let progress = res.progress;
            if (progress > 1) {
              if (progress < 100) {
                wx.showLoading({
                  title: '正在上传 ' + progress + '%'
                });
              } else {
                wx.hideLoading();
              }
            }
          });
        }
      })
    }
  
  },

  //人脸识别认证方法
  faceReTap: function () {
    var that = this;
    let url = app.globalRequestUrl('domainNameB', 'siteE');
    // var File_Path=that.data.fileUrl;
    var ValiCd=that.data.ValiCd;
    var endTime = new Date().getTime();// 视频结束的时间戳
    console.log("endTime:" + endTime); 
    var startTime = endTime - that.data.duration * 1000;// 视频开始的时间戳
    let data = {
      Mkt_ID: app.globalData.Mkt_ID,//市场编号
      WeCht_Idr: app.globalData.WeCht_Idr,//微信标识
      // File_Path: File_Path,//文件路径上送文件接口返回获取
      Ol_Sign_Jrnl_No: app.globalData.Ol_Sign_Jrnl_No,//在线签约流水号
      ValiCd: ValiCd,//验证码
      Vd_Rqs_Tm: that.data.duration,//视频请求时间
      Strt_Rcd_Tms: startTime,//开始录制时间戳
      End_Rcd_Tms: endTime,//结束录制时间戳
    };
    console.log("人脸识别接口上送" + JSON.stringify(data));
    app.appRequest('post', url, data, (res) => {
      var message = JSON.stringify(res);
      console.log("人脸识别接口返回1" + res.Txn_Rslt_Cd)
      // console.log("人脸识别接口返回2" + res)
      console.log("人脸识别接口返回2" + JSON.stringify(res))
      // wx.redirectTo({
      //   url: '/homepages/commonpages/successpage/successpage?type=1',
      // })
      //生产的时候打开，删掉上面
      if ((res.Txn_Rslt_Cd)=='00'){
        app.globalData.idnt_Ctfn_St = '02';//02标识视频认证成功
        wx.redirectTo({
          url: '/homepages/commonpages/successpage/successpage?type=1',
        })
      }else if (res.Txn_Rslt_Cd == "02") {
        wx.redirectTo({
          url: '/typechoosepage/typechoosepage',
        })
      }else{
        this.togglefailDialog();
      }

    }, (err) => {
      console.log('请求错误信息：  ' + err.errMsg);
      app.showErrormessage(err.errMsg);
    });

  } 
})